package net.osweb.core.tools.utils.ftp;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.http.HttpServletResponse;

import net.osweb.core.tools.dto.FtpDto;
import net.osweb.core.tools.exception.FileUploadException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import sun.net.ftp.FtpClient;





public class FtpFileUtil {

	private final transient static Log log = LogFactory
			.getLog(FtpFileUtil.class);

	public static boolean ftpFileUpload(File file, String ip, String ftpUser,
			String ftpPassword, String fileName, String ftpPath)
			throws FileUploadException {
		FtpClient ftpClient = null;
		OutputStream outputStream = null;
		InputStream inputStream = null;
		boolean flag = true;
		try {
			ftpClient = new FtpClient(ip);
			ftpClient.openServer(ip);
			ftpClient.login(ftpUser, ftpPassword);
			ftpClient.binary();
			try {
				ftpClient.cd(ftpPath);
			} catch (IOException e1) {
				ftpClient.sendServer("MKD " + ftpPath + "\r\n");
				try {
					ftpClient.readServerResponse();
				} catch (IOException e2) {
					throw new FileUploadException(e2);
				}
			}
			File fe = new File(fileName);
			outputStream = ftpClient.put(fe.getName());
			inputStream = new BufferedInputStream(new FileInputStream(file));
			byte[] bytes = new byte[1024];
			int readBye;
			while ((readBye = inputStream.read(bytes)) != -1) {
				outputStream.write(bytes, 0, readBye);
			}
		} catch (Exception e) {
			flag = false;
			log.error(e);
			throw new FileUploadException(e);
		} finally {
			try {
				if (outputStream != null)
					outputStream.flush();
				outputStream.close();
				if (inputStream != null)
					inputStream.close();
				ftpClient.closeServer();
			} catch (IOException e) {
				flag = false;
				log.error(e);
				throw new FileUploadException(e);
			}

		}
		return flag;
	}

	/**
	 * 
	 * @param fileName
	 * @param 上传
	 *            type = "0" 下载type = "1" 删除type = "2"
	 * @return
	 * @throws Exception
	 */
	private static FtpClient connectFtp() throws FileUploadException {
		FtpClient ftpClient = null;
		try {
			String ip = FileConfig.getInstance().getIp();
			String ftpPath = FileConfig.getInstance().getFtpPath();
			@SuppressWarnings("unused")
			String name = FileConfig.getInstance().getName();
			@SuppressWarnings("unused")
			String ftpPort = FileConfig.getInstance().getFtpPort();
			@SuppressWarnings("unused")
			String httpPort = FileConfig.getInstance().getHttpPort();
			@SuppressWarnings("unused")
			String httpPath = FileConfig.getInstance().getHttpPath();
			String ftpUser = FileConfig.getInstance().getFtpUser();
			String ftpPassword = FileConfig.getInstance().getFtpPassword();
			ftpClient = new FtpClient(ip);
			ftpClient.openServer(ip);
			ftpClient.login(ftpUser, ftpPassword);
			ftpClient.binary();
			@SuppressWarnings("unused")
			String filePath = "ftp://" + ip + "/" + ftpPath;
			ftpClient.cd(ftpPath);
			// ftpClient.readServerResponse();
		} catch (IOException e) {
			e.printStackTrace();
			log.error(e);
			try {
				ftpClient.closeServer();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
			throw new FileUploadException(e);
		}
		return ftpClient;
	}

	public static boolean ftpFileUpload2(FtpDto ftpDto)
	throws FileUploadException {
		
		FtpClient ftpClient = null;
		boolean flag = true;
		try {
			if (ftpDto != null && ftpDto.getIn() != null
					&& !"".equals(ftpDto.getAppPath())
					&& !"".equals(ftpDto.getFileName())
					&& !"".equals(ftpDto.getFilePath())
					&& !"".equals(ftpDto.getUserName())
					&& !"".equals(ftpDto.getUuid())) {
				ftpClient = FtpFileUtil.connectFtp();
				FtpFileUtil.isDirExist(ftpClient, ftpDto.getAppPath());
				FtpFileUtil.isDirExist(ftpClient, ftpDto.getFilePath());
				FtpFileUtil.isDirExist(ftpClient, ftpDto.getUuid());
				
				FtpFileUtil.upload(ftpClient, ftpDto.getFileName(), ftpDto.getIn());
			} else {
				log.error("ftpDto problem");
				throw new FileUploadException();
			}
			
		} catch (Exception e) {
			flag = false;
			log.error(e);
			throw new FileUploadException(e);
		} finally {
			try {
				if (ftpClient != null) {
					ftpClient.closeServer();
				}
			} catch (IOException e) {
				flag = false;
				log.error(e);
				try {
					logout(ftpClient);
				} catch (Exception e1) {
					e1.printStackTrace();
				}
			}
			
		}
		return flag;
	}
	
	public static boolean ftpFileUpload(FtpDto ftpDto)
			throws FileUploadException {
		
		FtpClient ftpClient = null;
		boolean flag = true;
		try {
			if (ftpDto != null && ftpDto.getFile() != null
					&& !"".equals(ftpDto.getFileName())
					&& !"".equals(ftpDto.getFilePath())
					&& !"".equals(ftpDto.getUserName())
					&& !"".equals(ftpDto.getUuid())) {
				ftpClient = FtpFileUtil.connectFtp();
				FtpFileUtil.isDirExist(ftpClient, ftpDto.getFilePath());
				FtpFileUtil.isDirExist(ftpClient, ftpDto.getUserName());
				FtpFileUtil.isDirExist(ftpClient, ftpDto.getUuid());
				// ftpClient.readServerResponse();

				FtpFileUtil.upload(ftpClient, ftpDto.getFileName(), ftpDto
						.getFile());
			} else {
				log.error("ftpDto problem");
				throw new FileUploadException();
			}

		} catch (Exception e) {
			flag = false;
			log.error(e);
			throw new FileUploadException(e);
		} finally {
			try {
				if (ftpClient != null) {
					ftpClient.closeServer();
				}
			} catch (IOException e) {
				flag = false;
				log.error(e);
				try {
					logout(ftpClient);
				} catch (Exception e1) {
					e1.printStackTrace();
				}
			}

		}
		return flag;
	}

	private static void upload(FtpClient ftpClient, String fileName, File file)
			throws FileUploadException {
		OutputStream outputStream = null;
		InputStream inputStream = null;
		try {
			File fe = new File(fileName);
			outputStream = ftpClient.put(fe.getName());
			inputStream = new BufferedInputStream(new FileInputStream(file));
			byte[] bytes = new byte[1024];
			int readBye;
			while ((readBye = inputStream.read(bytes)) != -1) {
				outputStream.write(bytes, 0, readBye);
			}
		} catch (IOException e) {
			e.printStackTrace();
			log.error(e);
			throw new FileUploadException(e);
		} finally {
			if (outputStream != null)
				try {
					outputStream.flush();
					outputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			if (inputStream != null)
				try {
					inputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}				
		}
	}
	
	private static void upload(FtpClient ftpClient, String fileName, InputStream inputStream)
	throws FileUploadException {
		OutputStream outputStream = null;
		try {
			File fe = new File(fileName);
			outputStream = ftpClient.put(fe.getName());
			inputStream = new BufferedInputStream(inputStream);
			byte[] bytes = new byte[1024];
			int readBye;
			while ((readBye = inputStream.read(bytes)) != -1) {
				outputStream.write(bytes, 0, readBye);
			}
		} catch (IOException e) {
			e.printStackTrace();
			log.error(e);
			throw new FileUploadException(e);
		} finally {
			if (outputStream != null)
				try {
					outputStream.flush();
					outputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			if (inputStream != null)
				try {
					inputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}				
		}
	}	

	public static boolean ftpFileDownload(FtpDto ftpDto,
			HttpServletResponse response) throws FileUploadException {
		FtpClient ftpClient = null;
		OutputStream outputStream = null;
		InputStream inputStream = null;
		boolean flag = true;
		try {
			String fileName = ftpDto.getFileName();
			ftpClient = connectFtp();
			ftpClient.cd(ftpDto.getFilePath());
			ftpClient.binary();
			inputStream = ftpClient.get(fileName);
			downloadFile2(inputStream, fileName);
		} catch (IOException e) {
			log.error(e);
			flag = false;
			throw new FileUploadException(e);
		} finally {
			try {
				if (inputStream != null)
					inputStream.close();
				if (outputStream != null)
					outputStream.close();
				ftpClient.closeServer();
			} catch (IOException e) {
				log.error(e);
				flag = false;
				throw new FileUploadException(e);
			}
		}
		return flag;
	}

	private static void downloadFile2(InputStream inputStream, String fileName) throws FileUploadException {
		
	}
	
	@SuppressWarnings("unused")
	private static void downloadFile(InputStream inputStream,
			HttpServletResponse response, String fileName)
			throws RuntimeException {
		try {
			response.reset();// 设置为没有缓�?
			response.setContentType("application/x-download;charset=GBK");
			response.setHeader("Content-Disposition", "attachment;filename="
					+ new String(fileName.getBytes("GB2312"), "8859_1"));
			// 进入服务器的指定目录
			OutputStream outputStream = response.getOutputStream();
			byte[] bytes = new byte[1024];
			int readBye;
			while ((readBye = inputStream.read(bytes)) != -1) {
				outputStream.write(bytes, 0, readBye);
			}
			outputStream.flush();
		} catch (IOException e) {
			log.error(e);
			throw new RuntimeException(e);
		}

	}

	public static boolean deleteFile(FtpDto ftpDto) throws FileUploadException {
		boolean flag = false;
		FtpClient ftpClient = null;
		try {
			ftpClient = connectFtp();
			ftpClient.cd(ftpDto.getFilePath());
			// ftpClient.cd("graduate");
			// ftpClient.cd("admin");
			// ftpClient.cd("4dd706f0fb074eb1b1907977f31ab9db");
			ftpClient.binary();
			ftpClient.sendServer("dele " + ftpDto.getFileName() + "\r\n");
			System.out.println(ftpClient.readServerResponse());
			flag = true;
		} catch (IOException e) {
			flag = false;
			log.error(e);
			throw new FileUploadException(e);
		} finally {
			if (ftpClient != null) {
				try {
					ftpClient.closeServer();
				} catch (Exception e) {
					try {
						logout(ftpClient);
					} catch (Exception e1) {
						log.error("ftp client shutdown error", e);
						e1.printStackTrace();
					}
				}
			}
		}
		return flag;
	}

	private static void logout(FtpClient ftpClient) throws FileUploadException {
		// 用ftpclient.closeServer()断开FTP出错时用下更语句�?�?
		ftpClient.sendServer(" QUIT\r\n ");
		try {
			@SuppressWarnings("unused")
			int reply = ftpClient.readServerResponse();
		} catch (IOException e) {
			log.error(e);
			throw new RuntimeException(e);
		}
		// 取得服务器的返回信息
	}

	/** 判断Ftp目录是否存在,如果不存在则创建目录 */
	private static void isDirExist(FtpClient ftpClient, String dir)
			throws FileUploadException {
		try {
			ftpClient.cd(dir); // 想不到什么好办法来判断目录是否存在，只能用异常了(比较�?).请知道的告诉我一声`
		} catch (IOException e1) {
			try {
				ftpClient.sendServer("MKD " + dir + "\r\n");
				ftpClient.cd(dir);
				ftpClient.readServerResponse();
			} catch (Exception e) {
				log.error(e);
				throw new FileUploadException(e);
			}
		}
	}

}
